<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Course JRuby Programs: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Ruby Study Notes - Best Ruby Guide, Ruby Tutorial" />
<meta name="keywords" content="jruby,jruby programs,jruby swing,ruby study notes,free ruby programming guide,ruby guide,free ruby programming course,best ruby guide,ruby tutorials,ruby tutorial,learn ruby,ruby,ruby on rails,ruby rails,ruby learning,ruby tutoring,learning ruby,ruby programming,ruby on rails development,ruby training" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />
<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="icon" type="image/ico" href="/images/favicon.ico" />
<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->

</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Ruby helps programmers have more fun!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="/blog/" title="Ruby blog of Ruby Learning site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="http://ruby-challenge.rubylearning.org/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">

            <div id="main">

                <div id="main-inner"><a name="TemplateInfo"></a>
                <h1>Course JRuby Programs</h1>

                <p>Here are all the programs that we would be discussing while learning JRuby at <a href="http://rubylearning.org/">rubylearning.org</a>.</p>


                <pre><code>#jruby01a.rb
JS = Java::java.lang.System

os   = JS.get_property 'os.name'
home = JS.get_property 'java.home'
mem  = Java::java.lang.Runtime.get_runtime.free_memory

puts "Running on #{os}"
puts "Java home is #{home}"
puts "#{mem} bytes available in JVM"</code></pre>

                <pre><code># jruby01.rb
require 'java'

#java_import 'java.util.Date'
java_import('java.util.Date') { |pkg,name| 'JDate' }
java_import 'java.text.DateFormat'

date = JDate.new
date_format = DateFormat.get_date_instance
date_us = date_format .format date
puts date_us</code></pre>

            <pre><code># jruby02.rb
require 'java'
java_import 'java.lang.String' do |package,name|
  "J#{name}"
end

ResourceBundle = java.util.ResourceBundle
Locale = java.util.Locale

lang = JString.new 'de'
country = JString.new 'DE'

cLocale = Locale.new lang, country
msg = ResourceBundle.get_bundle 'MessagesBundle', cLocale

puts msg.get_string 'greetings'
puts msg.get_string 'welcome'</code></pre>

            <pre><code># jruby03.rb
require 'java'
JFrame = javax.swing.JFrame
JLabel = javax.swing.JLabel
frame  = JFrame.new
jlabel = JLabel.new 'Hello World'
frame.add jlabel
frame.set_default_close_operation JFrame::EXIT_ON_CLOSE
frame.pack
frame.set_size 200, 200
frame.set_visible true</code></pre>

            <pre><code># jruby04.rb
require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
:adapter=> "jdbcmysql",
:host => "localhost",
:database=> "students",
:username => "root",
:password => ""
)

class Rubyist &lt; ActiveRecord::Base
end

Rubyist.create(:name => 'Mitali Talim', :city => "Nashville, Tenessee")
Rubyist.create(:name => 'Sunil Kelkar', :city => "Pune, India")
Rubyist.create(:name => 'Adam Smith', :city => "San Fransisco, USA")

participant = Rubyist.find(:first)
puts %{#{participant.name} stays in #{participant.city}}

Rubyist.find(:first).destroy</code></pre>

            <pre><code>// JRubyJSR223.java
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptContext;

public class JRubyJSR223
{
  public static void main(String[] args) throws Exception
  {
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine rubyEngine = m.getEngineByName("jruby");
    rubyEngine.getContext().setAttribute("label", new Integer(4), ScriptContext.ENGINE_SCOPE);
    rubyEngine.eval("puts 2 + $label");
  }
}


/*
To execute the program -
C:\>java -cp E:\jruby-1.1.3\lib\jruby.jar;E:\jruby-1.1.3\lib\jruby-engine.jar;.; JRubyJSR223
*/</code></pre>

            <pre><code>// JRubyJSR223Rx2.java
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.ScriptContext;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class JRubyJSR223Ex2
{
  public static void main(String[] args) throws ScriptException, FileNotFoundException
  {
    //list all available scripting engines
    listScriptingEngines();
    //get jruby engine
    ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
    //process a ruby file
    jruby.eval(new BufferedReader(new FileReader("myfact.rb")));
    //call a method defined in the ruby source
    jruby.put("number", 6);

    long fact = (Long) jruby.eval("fact($number)");
    System.out.println("fact: " + fact);

    jruby.eval("$myglobalvar = fact($number)");
    long myglob = (Long) jruby.getBindings(ScriptContext.ENGINE_SCOPE).get("myglobalvar");
    System.out.println("myglob: " + myglob);
  }

  public static void listScriptingEngines()
  {
    ScriptEngineManager mgr = new ScriptEngineManager();
    for (ScriptEngineFactory factory : mgr.getEngineFactories())
    {
      System.out.println("ScriptEngineFactory Info");
      System.out.printf("\tScript Engine: %s (%s)\n", factory.getEngineName(), factory.getEngineVersion());
      System.out.printf("\tLanguage: %s (%s)\n", factory.getLanguageName(), factory.getLanguageVersion());
      for (String name : factory.getNames())
      {
        System.out.printf("\tEngine Alias: %s\n", name);
      }
    }
  }
}


/*
To execute the program -
C:\>java -cp E:\jruby-1.1.3\lib\jruby.jar;E:\jruby-1.1.3\lib\jruby-engine.jar;.; JRubyJSR223Ex2
*/</code></pre>

            <pre><code># myfact.rb
# computes the factorial of a given number
def fact(n)
 if n==0
    return 1
 else
    return n*fact(n-1)
 end
end</code></pre>

            <pre><code># Assignment 1
# frontend.rb
require 'java'
require 'swing'
require 'awt'

class FrontEnd &lt; Swing::JFrame
  def initialize(title)
    super(title)
    initComponents
  end

  private
  def initComponents
    # Create all the UI objects
    flow_layout = Awt::FlowLayout.new(Awt::FlowLayout::LEFT)
    grid_layout = Awt::GridLayout.new(3,2)
    @l_panel = Swing::JPanel.new
    @label = Swing::JLabel.new 'A Simple Application'
    @main_panel = Swing::JPanel.new
    @main_panel.set_layout(grid_layout)
    @lid = Swing::JLabel.new 'LoginId'
    @lpass = Swing::JLabel.new 'Password'
    @lname = Swing::JLabel.new 'Message'
    @tid = Swing::JTextField.new(10)
    @tpass = Swing::JTextField.new(10)
    @tname = Swing::JTextField.new(20)
    @tname.set_editable(false)
    @p1 = Swing::JPanel.new
    @p1.set_layout(flow_layout)
    @p2 =Swing::JPanel.new
    @p2.set_layout(flow_layout)
    @p3 = Swing::JPanel.new
    @p3.set_layout(flow_layout)
    @p4 = Swing::JPanel.new
    @p4.set_layout(flow_layout)
    @p5 = Swing::JPanel.new
    @p5.set_layout(flow_layout)
    @p6 = Swing::JPanel.new
    @p6.set_layout(flow_layout)

    @p1.add(@lid)
    @p2.add(@tid)
    @p3.add(@lpass)
    @p4.add(@tpass)
    @p5.add(@lname)
    @p6.add(@tname)
    @main_panel.add(@p1)
    @main_panel.add(@p2)
    @main_panel.add(@p3)
    @main_panel.add(@p4)
    @main_panel.add(@p5)
    @main_panel.add(@p6)
    @l_panel.add(@label)

    @b = Swing::JButton.new("Submit")
    @br = Swing::JButton.new("Refresh")
    @b_panel = Swing::JPanel.new
    @b_panel.add(@b)
    @b_panel.add(@br)

    # Add the UI objects to the frame
    self.add(@l_panel, Awt::BorderLayout::NORTH)
    self.add(@main_panel, Awt::BorderLayout::CENTER)
    self.add(@b_panel, Awt::BorderLayout::SOUTH)

    # Show frame
    self.set_default_close_operation(Swing::WindowConstants::EXIT_ON_CLOSE)
    self.set_resizable(false)
    self.pack
    self.set_visible(true)
  end
end


# Usage
f = FrontEnd.new('Assignment 1')</code></pre>

            <pre><code># awt.rb
# Bundle Java AWT and AWT event packages for ease of reference
require 'java'

module Awt
  include_package 'java.awt'
  include_package 'java.awt.event'
end
</code></pre>

            <pre><code># swing.rb
# Bundle Swing API and Swing Layout Extension (require swing-layout-1.0.2.jar)
include Java

module Swing
  include_package 'javax.swing'
  include_package 'javax.swing.event'
end
</code></pre>

            <pre><code># Assignment 2
# Modified frontend.rb
# programs used: frontend.rb, backend.rb, awt.rb, swing.rb, clickaction.rb
require 'java'
require 'swing'
require 'awt'
require 'clickaction'

class FrontEnd &lt; Swing::JFrame
  def initialize(title)
    super(title)
    initComponents
  end

  def get_user_input
    return {'id' => @tid.get_text, 'pass' => @tpass.get_text}
  end

  def show_result result
    @tname.set_text(result)
  end

  def refresh_screen
    @tid.set_text("")
    @tpass.set_text("")
    @tname.set_text("")
    @tid.request_focus
  end

  private
  def initComponents
    # Create all the UI objects
    flow_layout = Awt::FlowLayout.new(Awt::FlowLayout::LEFT)
    grid_layout = Awt::GridLayout.new(3,2)
    @l_panel = Swing::JPanel.new
    @label = Swing::JLabel.new 'A Simple Application'
    @main_panel = Swing::JPanel.new
    @main_panel.set_layout(grid_layout)
    @lid = Swing::JLabel.new 'LoginId'
    @lpass = Swing::JLabel.new 'Password'
    @lname = Swing::JLabel.new 'Message'
    @tid = Swing::JTextField.new(10)
    @tpass = Swing::JTextField.new(10)
    @tname = Swing::JTextField.new(20)
    @tname.set_editable(false)
    @p1 = Swing::JPanel.new
    @p1.set_layout(flow_layout)
    @p2 =Swing::JPanel.new
    @p2.set_layout(flow_layout)
    @p3 = Swing::JPanel.new
    @p3.set_layout(flow_layout)
    @p4 = Swing::JPanel.new
    @p4.set_layout(flow_layout)
    @p5 = Swing::JPanel.new
    @p5.set_layout(flow_layout)
    @p6 = Swing::JPanel.new
    @p6.set_layout(flow_layout)

    @p1.add(@lid)
    @p2.add(@tid)
    @p3.add(@lpass)
    @p4.add(@tpass)
    @p5.add(@lname)
    @p6.add(@tname)
    @main_panel.add(@p1)
    @main_panel.add(@p2)
    @main_panel.add(@p3)
    @main_panel.add(@p4)
    @main_panel.add(@p5)
    @main_panel.add(@p6)
    @l_panel.add(@label)

    @b = Swing::JButton.new("Submit")
    @br = Swing::JButton.new("Refresh")
    @b_panel = Swing::JPanel.new
    @b_panel.add(@b)
    @b_panel.add(@br)

    @b.add_action_listener ClickAction.new(self)
    @br.add_action_listener ClickAction.new(self)

    # Add the UI objects to the frame
    self.add(@l_panel, Awt::BorderLayout::NORTH)
    self.add(@main_panel, Awt::BorderLayout::CENTER)
    self.add(@b_panel, Awt::BorderLayout::SOUTH)

    # Show frame
    self.set_default_close_operation(Swing::WindowConstants::EXIT_ON_CLOSE)
    self.set_resizable(false)
    self.pack
    self.set_visible(true)
  end
end


# Usage
f = FrontEnd.new('Assignment 2')</code></pre>

            <pre><code># clickaction.rb
require 'java'
require 'swing'
require 'awt'
require 'backend'
class ClickAction
  include Awt::ActionListener

  private
  attr_accessor :view

  def initialize(view)
    @view = view
    # Create the Login object
    @backend = Backend.new
  end

  public
  def actionPerformed(e)
    user_input = @view.get_user_input
    id = user_input['id']
    pass = user_input['pass']
    if ("Submit".eql?(e.get_action_command))
      result = @backend.authenticate_safely_simply(id, pass)
      @view.show_result result
    else
      @view.refresh_screen
    end
  end
end</code></pre>

            <pre><code># backend.rb
require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
:adapter=> "jdbcmysql",
:host => "localhost",
:database=> "assignments",
:username => "root",
:password => ""
)

class Backend &lt; ActiveRecord::Base
  def insert_records
    Backend.create(:loginid => '01', :password => 'satish', :name => "Satish Talim")
    Backend.create(:loginid => '02', :password => 'sunil', :name => "Sunil Kelkar")
    Backend.create(:loginid => '03', :password => 'fabio', :name => "Fabio Akita")
  end

  def find_first
    user = Backend.find(:first)
    puts %{#{user.name} is a valid user of the system}
  end

  # authenticate_safely_simply will sanitize the user_name and password before inserting them in the query,
  # which will ensure that an attacker can't escape the query and fake the login (or worse).
  def authenticate_safely_simply(loginid, password)
    #user = Backend.find(:first, :conditions => { :loginid => loginid, :password => password })
    # we could also use Dynamic Finders
    # begin
      # See note below
      user = Backend.find_by_loginid_and_password(loginid, password)
      if user.nil?
        # no such user, let them retry
        return "Sorry no such user..."
      else
        # log them in
        return "Welcome " + user.name
      end
=begin
      #puts %{#{user.name} is a valid user of the system}
      return "Welcome " + user.name
    rescue #ActiveRecord::RecordNotFound
      return "Sorry no such user..."
=end
    end
end

=begin
b = Backend.new
#b.insert_records
b.find_first
b.authenticate_safely_simply('02','sunil')
=end

=begin
create database assignments;
grant all on assignments.* to 'root'@'localhost';
use assignments;
drop table if exists backends;
create table backends (
  id int not null auto_increment,
  loginid  varchar(10) not null,
  password varchar(20) not null,
  name text not null,
  primary key (id)
);
=end

=begin
The method Backend.find_by_loginid_and_password(loginid, password)
This is a Dynamic finder and also a syntactic sugar in ActiveRecord.
Explanatuon - http://weblog.jamisbuck.org/2006/12/1/under-the-hood-activerecord-base-find-part-3
=end</code></pre>
            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">
            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->
    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
</div>

</body>
</html>
